package com.qf.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

@Controller
public class TestController {
    @RequestMapping("/download")
    public void download(HttpSession session, String filename, HttpServletResponse response) throws Exception {
        String realPath = session.getServletContext().getRealPath("img");
        FileInputStream fis = new FileInputStream(new File(realPath, filename));
        //设置响应头  告知浏览器，要以附件的形式保存内容   filename=浏览器显示的下载文件名
        response.setHeader("content-disposition","attachment;filename="+filename);
        IOUtils.copy(fis, response.getOutputStream());
    }
    @RequestMapping("/upload")
    public String upload(HttpSession session,String username, MultipartFile file){
        String uuid = UUID.randomUUID().toString();
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        String filename = uuid +"--"+ originalFilename;
        //动态获取服务器的路径
        //ServletContext servlet上下文对象（全局唯一）
        String realPath = session.getServletContext().getRealPath("img");
        File path = new File(realPath);
        if (path.exists()){
            path.mkdirs();
        }
        try {
            file.transferTo(new File(path,filename));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/success.jsp";
    }
}
